package com.example.androidcomplete0102.ch19;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.androidcomplete0102.R;

public class LooperEx extends Activity {
	TextView mMainTv;
	TextView mBackTv;
	EditText mEdit;
	int mainValue;
	CalThread thread;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_loopertest);
		mMainTv = (TextView)findViewById(R.id.looper_mainvalue);
		mBackTv = (TextView)findViewById(R.id.looper_backvalue);
		mEdit = (EditText)findViewById(R.id.looper_number);
		
		thread = new CalThread(mMainHandler);
		thread.setDaemon(true);
		thread.start();
	}
	
	public void mOnClick(View v){
		Message msg = null;
		switch(v.getId()){
		case R.id.looper_increase:
			mainValue++;
			mMainTv.setText("Main Value:"+mainValue);
			break;
		case R.id.looper_square:
			msg = Message.obtain(thread.mBackHanlder, 0, Integer.parseInt((mEdit.getText().toString())), 0);
			thread.mBackHanlder.sendMessage(msg);
			break;
		case R.id.looper_root:
			msg = Message.obtain(thread.mBackHanlder, 1, Integer.parseInt((mEdit.getText().toString())), 0);
			thread.mBackHanlder.sendMessage(msg);
			break;
		}
	}
	
	Handler mMainHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 0:
				mBackTv.setText("Square Result:"+msg.arg1);
				break;
			case 1:
				mBackTv.setText("Root Result:"+((Double)msg.obj).doubleValue());
				break;
			}
		}
		
	};
}

class CalThread extends Thread{
	Handler mManiHandler;
	Handler mBackHanlder;
	
	public CalThread(Handler mManiHandler) {
		this.mManiHandler = mManiHandler;
	}
	
	@Override
	public void run() {
		Looper.prepare();
		
		mBackHanlder = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				Message retMsg = Message.obtain();
				switch(msg.what){
				case 0:
					//retMsg = Message.obtain(mManiHandler, 0, msg.arg1 * msg.arg1, 0);
					retMsg.what = 0;
					retMsg.arg1 = msg.arg1 * msg.arg1;
					break;
				case 1:
					//retMsg = Message.obtain(mManiHandler, 0, msg.arg1 * msg.arg1, 0);
					retMsg.what = 1;
					retMsg.obj = new Double(Math.sqrt(msg.arg1));
					break;
				}
				mManiHandler.sendMessage(retMsg);
			}
			
		};
		
		Looper.loop();
	}
}